package com.google.code.mergeinformer.service.impl;

import com.google.code.mergeinformer.model.DefaultEntity;
import com.google.code.mergeinformer.service.ServiceBase;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.lang.reflect.ParameterizedType;

/**
 * @author Dmitry Golubev
 */
public abstract class ServiceBaseImpl<T extends DefaultEntity> implements ServiceBase<T> {

    private final Class<T> clazz;

    @PersistenceContext
    protected EntityManager em;

    @SuppressWarnings("unchecked")
    protected ServiceBaseImpl() {
        clazz = ((Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }

    @Override
    public T find(String id) {
        return em.find(clazz, id);
    }

    @Override
    @Transactional
    public void persist(T entity) {
        em.persist(entity);
    }

    @Override
    @Transactional
    public void remove(T entity) {
        em.remove(entity);
    }
}
